package com.graph;

import edu.princeton.cs.algs4.Bag;
import edu.princeton.cs.algs4.In;

public class DirectedDFS {

    private boolean [] marked;

    public DirectedDFS(Digraph G, int s) {
        marked = new boolean[G.V()];

        dfs(G, s);
    }

    private void dfs(Digraph g, int s) {
        if (marked[s])
            return;
        marked[s] = true;

        for (int w: g.adj(s)) {
            if (!marked[w]) {
                dfs(g, w);
            }
        }
    }


    public DirectedDFS(Digraph g, Iterable<Integer> sources) {
        marked = new boolean[g.V()];
        for (int w : sources) {
            dfs(g, w);
        }
    }

    public boolean marked (int v) {
        return marked[v];
    }

    public static void main(String[] args) {

        Digraph g = new Digraph(new In(args[0]));
        Bag<Integer> sources = new Bag<>();
        for (int i = 1; i < args.length; i++) {
            sources.add( Integer.parseInt(args[i]));
        }
        DirectedDFS reachable = new DirectedDFS(g, sources);

        for (int i = 0; i < g.V(); i++) {
            if (reachable.marked(i)) {
                System.out.print(i + " ");
            }
        }

        System.out.println();
    }
}
